#-*- encoding: utf-8 -*-
import win32com.client 
from Misc.Utils import *

from DataAccess.QueryBlp import *

from datetime import date,timedelta

from ReportTool.HldReport import *
from ReportTool.PnLReport import *
from ReportTool.NAVReport import *
from ReportTool.MktValReport import *
from ReportTool.TradeReport import *
from ReportTool.RealizedPnL import *
from ReportTool.OnshoreHldReport import *
from ReportTool.LongShortMktExposure import *

from Config.ReportConfig import *
from Common.Calendar import *

def LS_Mkt_Exposure_Report(portf_id, start_date, end_date, match_published_nav = False):

	r = LS_Mkt_Exposure(portf_id, start_date, end_date, match_published_nav)
	
	tplt_file = TPLT_PATH + 'Long Short Market Exposure Report.xls'
	xApp = win32com.client.Dispatch("Excel.Application")
	xBook = xApp.Workbooks.Open(tplt_file)
	xSht = xBook.Worksheets('Report')
	
	if not r:
		return
		
	row = 2
	for d in sorted(r.keys()):
		xSht.Cells(row, 1).Value = d
		xSht.Cells(row, 2).Value = r[d][0]
		xSht.Cells(row, 3).Value = r[d][1]
		xSht.Cells(row, 4).Value = r[d][2]
		
		row += 1
	
	rept_file = REPT_PATH + 'Long Short Market Exposure Report_''' + portf_id + '.xls'
	xBook.SaveAs(rept_file)
	xBook.Close()
	del xApp
	
	print 'info, long short market exposure report completed.'

def LS_Mkt_Exposure(portf_id, start_date, end_date, match_published_nav):

	if portf_id == 'SC008' or portf_id == 'SC010':
		entity = portf_id + '_A'
	elif portf_id == 'SC028':
		entity = portf_id + '_NONUS'
	else:
		entity = portf_id + '_F'
	
	nav_series = {}
	r = query_NAV_series(start_date, end_date, [entity], is_per_unit=True, is_official=match_published_nav)
	for elem in r:
		nav_series[elem[1].date()] = elem[2]

	if not nav_series:
		print 'nav series is empty'
		return
	
	d = start_date
	expo_series = {} #expo_series[d] = (long_expo, short_expo)
	while d <= end_date:
		
		if TradingCalendar().is_holiday(d):
			d += timedelta(days=1)
			continue
			
		if match_published_nav and (not nav_series.has_key(d)):
			d += timedelta(days=1)
			continue
		
		expo = query_ls_mkt_exposure(d, portf_id)
		long_expo = None
		short_expo = None
		for elem in expo:
			if elem[1] == 'LONG':
				long_expo = elem[2]
			if elem[1] == 'SHORT': 
				short_expo = elem[2]
			
		# hld = query_hld(d, [portf_id])
		
		# long_expo = 0.0
		# short_expo = 0.0
		# for elem in hld:
			# if elem[2] == 'CASH' or elem[2] == 'REPO':
				# continue
			
			# if elem[3] == 'LONG':
				# long_expo += elem[12]
				
			# if elem[3] == 'SHORT':
				# short_expo += elem[12]
		
		if nav_series.has_key(d):
			expo_series[d] = (nav_series[d], long_expo, short_expo)
		
		d += timedelta(days=1)
		
	return expo_series